package org.lex.tinyscript;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.lex.tinyscript.command.CommandParser;
import org.lex.tinyscript.command.ScriptCommand;

public class ScriptParser {
	public Collection<ScriptCommand> parse(File scriptFile)
			throws TinyScriptException {
		try {
			return this.parse(new BufferedReader(new FileReader(scriptFile)));
		} catch (FileNotFoundException e) {
			throw new TinyScriptException("script file not exists: "
					+ scriptFile, e);
		}
	}

	public Collection<ScriptCommand> parse(Reader reader)
			throws TinyScriptException {
		List<ScriptCommand> results = new ArrayList<ScriptCommand>();
		BufferedReader in = new BufferedReader(reader);
		CommandParser parser = new CommandParser();
		try {
			while (true) {
				String line = null;
				line = in.readLine();
				if (null == line) {
					break;
				} else {
					ScriptCommand command = parser.parse(line);
					if (null != command)
						results.add(command);
				}
			}
		} catch (IOException e) {
			throw new TinyScriptException("read script file I/O failed", e);
		} catch (CloneNotSupportedException e) {
			throw new TinyScriptException("parse ScriptCommand failed", e);
		}
		return results;
	}
}
